const CacheBlock = require('./CacheBlock')
const {env} =require('process')
class Cache{
    /**
     * 
     * @param {number} id Cache id（表示属于第几个处理机
     * @param {number} size 缓存块个数
     */
    constructor(id,size){
        this.id = id
        this.size = size
        this.cacheBlocks = Array(size).fill(0).map((v,i) => new CacheBlock(id,i))
    }

    read(content){ 
        if(env.lang === 'en')console.log(`processor ${this.id} read ${content}`)
        if(env.lang === 'zh')console.log(`处理机 ${this.id} 读内存 ${content}`)
        const target = this.cacheBlocks[content % this.size]
        if(target.content == content){
            console.log('读命中')
            target.prRd()
        }
        else {
            console.log('未命中')
            target.flush()
            target.changeState('Invalid')
            target.changeContent(content)
            target.prRd()
        }
    }

    write(content){
        if(env.lang === 'en')console.log(`processor ${this.id} write ${content}`)
        if(env.lang === 'zh')console.log(`处理机 ${this.id} 写内存 ${content}`)
        const target = this.cacheBlocks[content % this.size]
        if(target.content == content){
            console.log('写命中')
            target.prWr()
        }
        else {
            console.log('未命中')
            target.flush()
            target.changeState('Invalid')
            target.changeContent(content)
            target.prWr()
        }
    }
}

/**
 * 
 * @param {number} process_num 处理器个数
 * @param {number} cache_num 每个处理器缓存个数
 * @returns 返回整个系统
 */
module.exports.CachesBuilder = (process_num,cache_num)=>{
    console.log('系统初始化')
    let sys = Array(process_num).fill(0).map((v,i)=> new Cache(i,cache_num))
    console.log(`当前系统为${process_num}处理机，每个处理机${cache_num}个缓存块`)
    return sys
}